package com.game.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;

import com.game.model.Card;
import com.game.model.GameRoom;
import com.game.model.Player;

@Service
public class GameService {
    private final Map<String, GameRoom> gameRooms = new ConcurrentHashMap<>();

    public GameRoom createRoom() {
        GameRoom room = new GameRoom();
        gameRooms.put(room.getId(), room);
        return room;
    }

    public GameRoom getRoom(String roomId) {
        return gameRooms.get(roomId);
    }

    public void deleteRoom(String roomId) {
        gameRooms.remove(roomId);
    }

    public void startGame(String roomId) {
        GameRoom room = getRoom(roomId);
        if (room != null && room.getStatus() == GameRoom.GameStatus.WAITING) {
            // 检查玩家数量
            if (room.getPlayers().size() < 2 || room.getPlayers().size() > 4) {
                throw new IllegalStateException("玩家数量必须在2-4人之间");
            }
            
            room.initializeDeck();
            Collections.shuffle(room.getDeck());
            dealCards(room);
            room.setStatus(GameRoom.GameStatus.PLAYING);
        }
    }

    private void dealCards(GameRoom room) {
        List<Player> players = room.getPlayers();
        int playerCount = players.size();
        
        // 确保每个玩家获得13张牌
        for (int i = 0; i < playerCount; i++) {
            List<Card> playerCards = new ArrayList<>();
            for (int j = 0; j < 13; j++) {
                playerCards.add(room.getDeck().remove(0));
            }
            players.get(i).setCards(playerCards);
        }
    }

    public void submitHand(String roomId, String playerId, List<Card> frontHand, List<Card> middleHand, List<Card> backHand) {
        GameRoom room = getRoom(roomId);
        if (room != null) {
            Player player = room.getPlayers().stream()
                    .filter(p -> p.getId().equals(playerId))
                    .findFirst()
                    .orElse(null);
            
            if (player != null) {
                // TODO: 验证牌型并计算分数
                player.setReady(true);
                checkGameEnd(room);
            }
        }
    }

    private void checkGameEnd(GameRoom room) {
        boolean allReady = room.getPlayers().stream().allMatch(Player::isReady);
        if (allReady) {
            room.setStatus(GameRoom.GameStatus.FINISHED);
            // TODO: 计算最终分数
        }
    }
} 